const db = require('../db/index');
const moment = require('moment');

exports.addConsumption = (req, res) => {
  const { amount, category, time, imageUrl } = req.body;
  const sql = 'INSERT INTO consumption_records (user_id, amount, category, time, image_url) VALUES (?, ?, ?, ?, ?)';
  db.query(sql, [req.user.id, amount, category, moment(time).format('YYYY-MM-DD HH:mm:ss'), imageUrl], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) return res.cc('添加消费凭证失败');
    res.cc('添加消费凭证成功', 0);
  });
};

exports.getConsumptions = (req, res) => {
  const sql = 'SELECT * FROM consumption_records WHERE user_id = ?';
  db.query(sql, [req.user.id], (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: '获取消费凭证成功',
      data: results
    });
  });
};